package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.rpc.UserInfoService;
import com.pms.service.IBaseUserService;
import com.pms.service.ISysNoticeService;
import com.pms.service.ISysNoticeUserService;
import com.pms.util.PhoneUtils;
import com.pms.validator.Assert;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ljb
 * @since 2018-07-17
 */
@RestController
@RequestMapping("/sysNotice")
@Api(value = "系统通知模块",description = "系统通知模块")
public class SysNoticeController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private IBaseUserService iBaseUserService;

    @Autowired
    private ISysNoticeService iSysNoticeService;
    @Autowired
    private ISysNoticeUserService iSysNoticeUserService;

    @PostMapping("/add")
    @ApiOperation("发公告")
    @ApiImplicitParams({
            @ApiImplicitParam(name="SysNotice",value="通告实体类",required = true,dataType = "String",paramType="form")
    })
    public R addSysNotice(@RequestBody SysNotice sysNotice,
                          @RequestHeader("X-Name") String userName,
                          @RequestHeader("X-Code") String companyCode){
        parameterIsNull(sysNotice.getSource(),"请选择所属系统");
        parameterIsNull(sysNotice.getTitle(),"公告标题不能为空");
        parameterIsNull(sysNotice.getInfo(),"公告内容不能为空");
        parameterIsNull(sysNotice.getStartTime(),"公告生效时间");
//        parameterIsNull(sysNotice.getEndTime(),"公告结束时间");
        sysNotice.setStatus(1);
        sysNotice.setCreateTime(new Date());

        BaseUser user = iBaseUserService.getUserByUsername(userName,companyCode);
        sysNotice.setCreatorId(Long.valueOf(user.getId()));
        sysNotice.setCompanyCode(user.getCompanyCode());

        iSysNoticeService.insertAndUser(sysNotice);
        return R.ok();
    }

    @ApiOperation(value = "通知详情")
    @RequestMapping(value = "/{noticeId}",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="noticeId", value="公告id",required = true,dataType = "String",paramType="form")
    })
    public R detail(@PathVariable String noticeId){
        SysNotice notice = iSysNoticeService.selectById(noticeId);
        BaseUser user = iBaseUserService.selectById(notice.getCreatorId());
        return R.ok().put("notice",notice).put("userName",user.getUsername());
    }

    @ApiOperation(value = "修改通知内容")
    @RequestMapping(value = "/updateNotice",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="SysNotice",value="通告实体类",required = true,dataType = "String",paramType="form")
    })
    public R update(@RequestBody SysNotice sysNotice,
                    @RequestHeader("X-Name") String userName,
                    @RequestHeader("X-Code") String companyCode){
        Assert.isNull(sysNotice.getId(),"公告id 不能为空");
        EntityWrapper<SysNoticeUser> ew = new EntityWrapper<SysNoticeUser>();
        iSysNoticeService.updateById(sysNotice);
        return R.ok();
    }

    @ApiOperation(value = "删除通知")
    @RequestMapping(value = "/{noticeId}",method = RequestMethod.DELETE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="noticeId", value="公告id",required = true,dataType = "String",paramType="form")
    })
    public R delete(@PathVariable String noticeId){
        iSysNoticeService.deleteById(Long.valueOf(noticeId));
        iSysNoticeUserService.deleteByNoticeId(Long.valueOf(noticeId));
        return R.ok();
    }



    @ApiOperation(value = "获取公告list")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="current",value="当前页",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="size",value="每页条数",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="content",value="模糊查询字段",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="source",value="所属系统",required = true,dataType = "Integer",paramType="form")
    })
    public R list(Integer current, Integer size, String content,
                  Integer source, Integer isEff,
                  @RequestHeader("X-Name") String userName,
                  @RequestHeader("X-Code") String companyCode){

        parameterIsNull(current,"current 不能为空");
        parameterIsNull(size,"size 不能为空");
        parameterIsNull(source,"source 不能为空");

        EntityWrapper<Map<String,Object>> ew = new EntityWrapper<Map<String,Object>>();
        if (StrUtil.isNotEmpty(content)){
            ew.like("sn.title", content);
        }
        ew.eq("sn.status", "1");
        ew.eq("sn.source", source);
        ew.eq("sn.company_code", companyCode);
        BaseUser user = iBaseUserService.getUserByUsername(userName,companyCode);
        ew.eq("snu.userId", user.getId());
        if (isEff != null) {
            ew.and("startTime < NOW()");
        }
        ew.orderBy("snu.isRead desc");
        ew.orderBy("sn.createTime desc");

        Page<Map<String,Object>> page = new Page(current, size);
        page = iSysNoticeService.selectSysNoticeMapsPage(page,ew);
        return R.ok().put("page",page);

    }

    @ApiOperation(value = "修改为已读")
    @RequestMapping(value = "/updateToReade",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="noticeId", value="公告id",required = true,dataType = "String",paramType="form")
    })
    public R updateToReade(String noticeId,
                           @RequestHeader("X-Name") String userName,
                           @RequestHeader("X-Code") String companyCode){
        Assert.isBlank(noticeId,"noticeId 不能为空");
        EntityWrapper<SysNoticeUser> ew = new EntityWrapper<SysNoticeUser>();
        ew.in("noticeId", noticeId);
        BaseUser user = iBaseUserService.getUserByUsername(userName,companyCode);
        ew.eq("userId", user.getId());

        List<SysNoticeUser> records = iSysNoticeUserService.selectList(ew);
        for (SysNoticeUser record:records){
            record.setIsRead(1);
        }
        iSysNoticeUserService.updateBatchById(records);
        return R.ok();
    }

    @ApiOperation(value = "查询所有未读的数据")
    @RequestMapping(value = "/getNotReade",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="source",value="所属系统",required = true,dataType = "Integer",paramType="form")
    })
    public R countNoReade(Integer source,
                          @RequestHeader("X-Name") String userName,
                          @RequestHeader("X-Code") String companyCode){
        Assert.isNull(source,"source 不能为空");
        BaseUser user = iBaseUserService.getUserByUsername(userName,companyCode);
        Integer count = iSysNoticeUserService.selectCountNotReade(user.getId(),source,companyCode);
        return R.ok().put("count",count);
    }


}
